package com.kuangjia.scenic_spot_ticket.controller;

import com.kuangjia.scenic_spot_ticket.common.Result;
import com.kuangjia.scenic_spot_ticket.dto.UserInfoDTO;
import com.kuangjia.scenic_spot_ticket.entity.User;
import com.kuangjia.scenic_spot_ticket.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;
import java.util.Map;

@RestController
@RequestMapping("/api")
public class AuthController {
    @Autowired
    private UserService userService;
    @Autowired
    private PasswordEncoder passwordEncoder;

    @PostMapping("/login")
    public Result<UserInfoDTO> login(@RequestBody Map<String, String> loginData) {
        String username = loginData.get("username");
        String password = loginData.get("password");
        
        User user = userService.lambdaQuery().eq(User::getUsername, username).one();
        if (user == null) {
            return Result.error("用户不存在");
        }
        
        // 验证密码
        if (!passwordEncoder.matches(password, user.getPassword())) {
            return Result.error("密码错误");
        }
        
        UserInfoDTO dto = new UserInfoDTO(user.getId(), user.getUsername(), user.getRole(), user.getBalance());
        return Result.success(dto);
    }
} 